<template>
    <div class="map-box">
        <div class="alarm-info-box">
            <alarm-info/>
        </div>
        <div class="home-map-legend-box">
            <home-map-legend v-model="selectedValueList"/>
        </div>
        <div id="homeMapContainer"></div>
    </div>
</template>

<script>
import {getInfoWindowByData, getMarkerByData, initMap, loadMap} from "@/utils/map";
import AlarmInfo from "@/views/home-map/components/AlarmInfo.vue";
import HomeMapLegend from "@/views/home-map/components/HomeMapLegend.vue";
import {allData} from "@/utils/data";

export default {
    name: "HomeMap",
    components: {
        AlarmInfo,
        HomeMapLegend
    },
    data() {
        return {
            selectedValueList:[0,1,2,3]
        }
    },
    watch: {
        // 根据图例，选择合适的地图控制他的显示和隐藏
        selectedValueList() {
            this.controlFlagDisplay();
        },
    },
    methods: {
        init() {
            loadMap([]).then((AMap) => {
                this.map = initMap(AMap, "homeMapContainer");
                // 每有一个数据应该有一个点
                this.markers = allData.map(item => {
                    const marker = getMarkerByData(AMap, item);
                    const infoWindow = getInfoWindowByData(AMap, item,()=>{
                        this.map.clearInfoWindow();
                    });
                    AMap.Event.addListener(marker, 'click', () => {
                        infoWindow.open(this.map, marker.getPosition());
                    });
                    return marker
                })
                this.map.add(this.markers)
                this.controlFlagDisplay();
            }).catch(e => {
                console.log(e);
            })
        },
        controlFlagDisplay() {
            // 根据我们上述的数据来控制它的显示和隐藏
            allData.forEach((item,index)=>{
                if (this.selectedValueList.includes(item.type)) {
                    // 应该显示
                    if (!this.markers[index].getMap()) {
                        this.markers[index].setMap(this.map)
                    }
                }else {
                    // 应该隐藏
                    this.markers[index].setMap(null)
                }
            })
        },
    },
    mounted() {
        this.init()
    }
}
</script>

<style scoped>
.map-box {
    height: 100vh;
    width: 100%;
    position: relative;
}

.alarm-info-box {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 9;
}

.home-map-legend-box {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 9;
}

#homeMapContainer {
    height: 100%;
    width: 100%;
}
</style>